from django.contrib.auth import authenticate, login
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render,redirect
from django.core.cache import cache

from apps.config.models import Menu_model, Role_model, Dept_model, Jobs_model
from apps.business.models import Contract_papers_model
from apps.config.serializers import Menu_serializer
from apps.users import models
from apps.users.models import Users_model

# 默认密码
default_password='123456'
# 登录校验
def login_check(request):
    # 需要判断获取类型,这里POST为表单登录提交类型，必须为大写
    if(request.method=='POST'):
        u_name = request.POST.get('username')
        u_pass = request.POST.get('password')
        user_obj = authenticate(username=u_name, password=u_pass)
        if not user_obj or user_obj.is_active==False:
            return render(request, 'login.html', {'errormsg':'用户名或者密码错误或被禁止登陆!'})
        else:
            cache.set('code', user_obj.user_code, timeout=60*60) #缓存时间30分钟
            login(request, user_obj)
            # 这里存
            code = request.user
            # 通过user查找正常显示存在的role角色的id
            user_obj = Users_model.objects.get(user_code=code)
            role_list = user_obj.user_role.filter().values_list('id', flat=True)
            # 这里用以查询他对于表单拥有的操作权限
            menu_list = Menu_model.objects.filter(role_model__id__in=role_list).distinct().exclude(menu_marital__in=['01', '02'])
            cache.set('menu_list',menu_list,timeout=None)
            return redirect('/index/')
    else:
        return render(request, 'login.html')

# 登录退出
def login_out(request):
    key = request.session.session_key
    request.session.delete(key)
    return JsonResponse({'code':0})

# 人员管理
def users_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request,'users/list.html',{'data1': menu_obj.data})

# 获得所有user数据
def users_list(request):
    try:
        user_list = Users_model.objects.filter()
        count = Users_model.objects.count()
    except Exception as e:
        return JsonResponse({'code':201,'msg':'users全查询出现问题，请联系管理员！'})
    list1 = []
    for i in user_list:
        user_obj = Users_model.objects.get(id=i.id)
        # 查他的角色
        roles = user_obj.user_role.filter().values_list('role_name',flat=True)
        roles_id = user_obj.user_role.filter().values_list('id', flat=True)
        new_role = list(roles)
        localpath = 'http://localhost:8000/media/'
        dept_id = i.user_dept.filter().values_list('id',flat=True)
        dict = {}
        dict['id'] = i.id
        dict['user_code'] = i.user_code
        dict['username'] = i.username
        dict['is_active'] = i.is_active
        dict['user_mobile'] = i.user_mobile
        dict['email'] = i.email
        dict['jobs'] = list(user_obj.user_job.values_list('job_name',flat=True))
        dict['job_id'] = list(user_obj.user_job.values_list('id',flat=True))
        dict['dept_id'] = list(dept_id)
        dict['roles_id'] = list(roles_id)
        dict['userid'] = i.user_id
        dict['remark'] = i.remark_describe
        dict['roles'] = new_role
        dict['is_sign'] = i.sign_power
        dict['dept'] = list(user_obj.user_dept.values_list('dept_name',flat=True)) # 这里查询其所在部门
        dict['user_avatar'] = localpath+str(i.user_avatar)
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！', 'count': count, 'data': res}
    return JsonResponse(Result)

# 添加页面的展示
def users_insert_view(request):
    return render(request, 'users/insert.html')

# 用于显示添加页面角色下拉框
def users_roles(request):
    try:
        roles = Role_model.objects.filter().order_by('role_order')
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'users角色查询模块出现问题，请联系管理员！'})
    list1 = []
    for i in roles:
        menu_id = i.role_menu.filter().values_list('id', flat=True)
        dict = {}
        dict['value'] = i.id
        dict['name'] = i.role_name
        dict['selected'] = 'false'
        list1.append(dict)
    return JsonResponse({'code': 0, 'msg': '成功！','data': list1})

# users添加动作
@transaction.atomic
def users_insert(request):
    # 先得判断是否具有添加权限（50500401）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500401' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('user_code')
    name = request.POST.get('username')
    idcard = request.POST.get('user_id')
    mobile = request.POST.get('user_mobile')
    dept = request.POST.get('dept')
    jobs = request.POST.get('jobs')
    email = request.POST.get('email')
    role = request.POST.get('select')
    is_sign = request.POST.get('is_sign')
    remark = request.POST.get('remark_describe')
    now_role = list(role)
    now_dept = list(dept)
    now_job = list(jobs)
    for i in now_role:
        if i == ',':
            now_role.remove(i)
    for k in now_dept:
        if k == ',':
            now_dept.remove(k)
    for m in now_job:
        if m == ',':
            now_job.remove(m)
    remark = request.POST.get('remark_describe')
    try:
        role_obj_list = Role_model.objects.filter(id__in=now_role)
        dept_obj_list = Dept_model.objects.filter(id__in=now_dept)
        jobs_obj_list = Jobs_model.objects.filter(id__in=now_job)
        user_obj = Users_model.objects.create(user_code=code,username=name,user_id=idcard,user_mobile=mobile,email=email,is_active=1,remark_describe=remark,sign_power=is_sign)
        user_obj.user_role.add(*role_obj_list)
        user_obj.user_dept.add(*dept_obj_list)
        user_obj.user_job.add(*jobs_obj_list)
        user_obj.set_password(default_password) # 设置默认密码
        user_obj.save()
    except Exception as aaa:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if aaa.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if aaa.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查雇员ID/手机号/身份证/邮箱字段。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# 修改页面
def users_edit_view(request):
    return render(request, 'users/edit.html')

# 修改动作
@transaction.atomic
def users_edit(request,id):
    # 先得判断是否具有添加权限（50500402）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500402' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('user_code')
    name = request.POST.get('username')
    mobile = request.POST.get('user_mobile')
    uid = request.POST.get('user_id')
    sign = request.POST.get('is_sign')
    roles = request.POST.get('role')
    now_role = str(roles).split(',')
    jobs = request.POST.get('jobs')
    now_job = str(jobs).split(',')
    email = request.POST.get('email')
    depts = request.POST.get('dept')
    now_dept = str(depts).split(',')
    remark = request.POST.get('remark_describe')
    try:
        user_obj = Users_model.objects.get(pk=id)
        depts_objs = Dept_model.objects.filter(id__in=now_dept)
        roles_objs = Role_model.objects.filter(id__in=now_role)
        jobs_objs = Jobs_model.objects.filter(id__in=now_job)
        user_obj.user_code = code
        user_obj.username = name
        user_obj.user_mobile = mobile
        user_obj.user_id = uid
        user_obj.email = email
        user_obj.sign_power = sign
        user_obj.remark_describe = remark
        user_obj.user_role.clear()
        user_obj.user_role.add(*roles_objs)
        user_obj.user_dept.clear()
        user_obj.user_dept.add(*depts_objs)
        user_obj.user_job.clear()
        user_obj.user_job.add(*jobs_objs)
        user_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查雇员ID/身份证号/手机号/邮箱地址。'})
        else:
            return JsonResponse({'code': 203, 'msg': 'menu修改模块出现问题，请联系管理员！'})

    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# 重置密码模块
@transaction.atomic
def users_resetpass(request,user_code):
    # 先得判断是否具有添加权限（50500403）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500403' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        user_obj=Users_model.objects.get(user_code=user_code)
        user_obj.set_password(default_password)
        user_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code':201,'msg':'user模块重置密码出现问题，请联系管理员！'})
    return JsonResponse({'code':0,'msg':'重置密码成功！'})

# 听启用模块
@transaction.atomic
def users_del(request,id):
    # 先得判断是否具有添加权限（50500404）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500404' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        user_obj = Users_model.objects.get(pk=id)
        if user_obj.is_active==False:
            user_obj.is_active=True
            user_obj.save()
            msg='启用成功！'
        else:
            user_obj.is_active = False
            user_obj.save()
            msg = '禁用成功！'
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 201, 'msg': 'user模块禁启用出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': msg})

# 查询
def users_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name) == 0:
            user_list = Users_model.objects.filter()
        else:
            # 支持用户名/雇员代码/邮箱/手机号模糊查询
            user_list = Users_model.objects.filter(Q(username__contains=name) | Q(user_code__contains=name) | Q(email__contains=name) | Q(user_mobile__contains=name))
        count = len(list(user_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'user单查模块出现问题，请联系管理员！'})
    list1 = []
    for i in user_list:
        user_obj = Users_model.objects.get(id=i.id)
        # 查他的角色
        roles = user_obj.user_role.filter().values_list('role_name', flat=True)
        roles_id = user_obj.user_role.filter().values_list('id', flat=True)
        new_role = list(roles)
        localpath = 'http://localhost:8000/media/'
        dept_id = i.user_dept.filter().values_list('id', flat=True)
        dict = {}
        dict['id'] = i.id
        dict['user_code'] = i.user_code
        dict['username'] = i.username
        dict['is_active'] = i.is_active
        dict['user_mobile'] = i.user_mobile
        dict['email'] = i.email
        dict['dept_id'] = list(dept_id)
        dict['roles_id'] = list(roles_id)
        dict['userid'] = i.user_id
        dict['remark'] = i.remark_describe
        dict['roles'] = new_role
        dict['dept'] = list(user_obj.user_dept.values_list('dept_name', flat=True))  # 这里查询其所在部门
        dict['user_avatar'] = localpath + str(i.user_avatar)
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})


def users_list1(request):
    try:
        user_list = Users_model.objects.filter()
        count = Users_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'users全查询出现问题，请联系管理员！'})
    list1 = []
    for i in user_list:
        user_obj = Users_model.objects.get(id=i.id)
        # 查他的角色
        roles = user_obj.user_role.filter().values_list('role_name', flat=True)
        roles_id = user_obj.user_role.filter().values_list('id', flat=True)
        new_role = list(roles)
        localpath = 'http://localhost:8000/media/'
        dept_id = i.user_dept.filter().values_list('id', flat=True)
        dict = {}
        dict['id'] = i.id
        dict['showname'] = i.username+'-'+list(i.user_dept.values_list('dept_name',flat=True))[0]
        list1.append(dict)
    Result = {'code': 0, 'msg': '成功！', 'count': count, 'data': list1}
    return JsonResponse(Result)

# 查询可以签字的人
def users_sign(request):
    try:
        rep_list = models.Users_model.objects.filter(sign_power=0)
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '获取约定书数据失败，请联系管理员'})
    list = []
    for i in rep_list:
        dict = {}
        dict['id'] = i.id
        dict['user_name'] = i.username+'/'+i.user_code
        list.append(dict)
    Result = {'code': 0, 'mes': '成功！', 'data': list}
    return JsonResponse(Result)

# 查询某个部门下的员工
def dept_users(request):
    # 查询到不为空的数据
    try:
        code = request.GET.get('paper_code')
        con_obj = Contract_papers_model.objects.get(paper_code=code)
        dept_list = Dept_model.objects.filter(tree_dept__isnull=False)
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '获取部门下员工数据失败，请联系管理员'})
    dept = []
    for i in dept_list:
        dict1 = {}
        dict1['value'] = i.dept_code
        dict1['name'] = i.dept_name
        user_list = Users_model.objects.filter(user_dept=i.id)
        children = []
        for k in user_list:
            dict2 = {}
            dict2['value'] = k.user_code
            dict2['name'] = k.username
            if k.user_code==con_obj.paper_manager.user_code:
                dict2['disabled'] = 'true'
            children.append(dict2)
            dict1['children'] = children
        dept.append(dict1)
    return JsonResponse({'code':0,'data':dept})